package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient  cacheClient;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 根据id查询商户信息
     * @param id
     * @return
     */
    @Override
    public Result queryById(Long id) {
        // 互斥锁解决缓存击穿
        // Shop shop = queryWithMutex(id);

        // 逻辑过期解决缓存击穿问题
        // Shop shop = queryWithLogicalExpire(id);

        // 工具类解决缓存穿透
        Shop shop = cacheClient.queryWithCacheNull(CACHE_SHOP_KEY, id, Shop.class, id2 -> getById(id),CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // 工具类解决缓存击穿
        //Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById,
        //                                               CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if (shop == null) {
            return Result.fail("当前商户不存在!");
        }
        return Result.ok(shop);
    }

    /**
     * 查询商铺（逻辑过期解决缓存击穿问题）
     * @param id
     * @return
     */
    private Shop queryWithLogicalExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 查询redis缓存是否存在对应数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(shopJson)) {
            // 不存在，直接返回
            return null;
        }
        // 反序列化json为shop
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        // 缓存中存在对应数据，判断是否过期
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 未过期，则返回
            return shop;
        }

        // 过期，尝试加锁
        if (tryLock(id)) {
            // 加锁成功，开启一个线程进行缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    loadShopCache(id, 10L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放锁
                    unLock(id);
                }
            });
        }

        // 返回
        return shop;
    }

    /**
     * 加载数据至缓存
     * @param id
     */
    public void loadShopCache(Long id, Long expire) {
        // 查询数据库
        Shop shop = getById(id);
        // 封装expireTime
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plus(expire, ChronoUnit.SECONDS));
        // 写入缓存
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }


    /**
     * 查询商铺（互斥锁解决缓存击穿）
     * @param id
     * @return
     */
    private Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 查询redis缓存是否存在对应数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJson)) {
            // 存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        if ("".equals(shopJson)) {
            // 查询到空缓存，返回错误信息
            return null;
        }

        Shop shop = null;
        // 不存在，加互斥锁
        boolean flag = tryLock(id);
        if (!flag) {
            // 未成功获取锁，循环等待
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return queryWithMutex(id);
        }
        // 获取锁成功，查询数据库是否有对应数据
        System.out.println("加锁成功");
        shop = getById(id);
        if (shop == null) {
            // 不存在，将空值写入缓存，并返回错误信息
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 存在，将数据库数据写入缓存
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // 释放锁
        unLock(id);
        System.out.println("释放锁成功");


        // 返回
        return shop;
    }

    /**
     * 尝试获取分布式锁
     * @param id
     * @return
     */
    private boolean tryLock(Long id) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(LOCK_SHOP_KEY + id, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁
     * @param id
     */
    private void unLock(Long id) {
        stringRedisTemplate.delete(LOCK_SHOP_KEY + id);
    }

    /**
     * 查询商铺（缓存空值解决缓存穿透）
     * @param id
     * @return
     */
    private Shop queryWithCacheNull(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 查询redis缓存是否存在对应数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJson)) {
            // 存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        if ("".equals(shopJson)) {
            // 查询到空缓存，返回错误信息
            return null;
        }
        // 不存在，查询数据库是否有对应数据
        Shop shop = getById(id);
        if (shop == null) {
            // 不存在，将空值写入缓存，并返回错误信息
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 存在，将数据库数据写入缓存
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // 返回
        return shop;
    }

    /**
     * 更新店铺信息
     * @param shop
     * @return
     */
    @Transactional
    @Override
    public Result updateShop(Shop shop) {
        // 更新数据库
        updateById(shop);
        // 删除redis缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());

        return Result.ok();
    }
}
